package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.jiabei.util.JbStringUtil;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.service.payment.qicai.util.QCSignUtil;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.HttpServletRequestUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@RequestMapping("/v/qc/pay")
@RestController
public class QCPayNotifyController extends BasePayNotifyController {

    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        super.notifyAsync(request,response,orderno);
    }

    @RequestMapping("/returns")
    public void returns(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        super.notifySync(request,response,orderno);
    }

    @Override
    protected void notifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        String orderno = "";
        try {
            pw = response.getWriter();
            Map<String, String> reqParmMap = HttpServletRequestUtil.getRequestParameters(request);
            orderno = reqParmMap.get("ordernumber");

            LogPortal.info("{} 七彩交易异步通知 参数:{}", traceId,reqParmMap);
            if (StringUtils.isEmpty(orderno)) {
                LogPortal.info("{} 七彩交易异步通知 订单号数值为空，不进行后续操作", traceId);
                return;
            }
            Order order = orderService.selectByMerchantOrderNo(orderno);
            if (order == null) {
                LogPortal.error("{} 七彩交易异步通知 订单号[{}]在我方系统查询不到", traceId, orderno);
                return;
            }
            String KeyValue = systemInitialization.channelDTO(order.getPayChannleId()).getChannelKey();
            String channelOrderNo = reqParmMap.get("sysnumber");
            Map<String,String> signParamMap = new LinkedHashMap<>();
            signParamMap.put("partner",reqParmMap.get("partner"));
            signParamMap.put("ordernumber",reqParmMap.get("ordernumber"));
            signParamMap.put("orderstatus",reqParmMap.get("orderstatus"));
            signParamMap.put("paymoney",reqParmMap.get("paymoney"));

            String signVer = QCSignUtil.getSign(traceId,"七彩交易异步通知",signParamMap,KeyValue);

            String status = reqParmMap.get("orderstatus");
            OrderStatus orderStatus;
            if (reqParmMap.get("sign").equals(signVer.trim())) {
                if ("1".equals(status)) {
                    orderStatus = OrderStatus.SUCCESS;
                }else {
                    orderStatus = OrderStatus.FAIL;
                }
                if (OrderStatus.PROCESSING.equals(order.getOrderStatus())) {
                    String XY_GAME_PAY_LOCK_FLAG= System.getenv("XY_GAME_PAY_LOCK_FLAG");
                    String orderLockName = "orderLock".concat(this.getClass().getSimpleName()).concat(XY_GAME_PAY_LOCK_FLAG).concat(orderno);
                    boolean orderLock=false;
                    try {
                        if (orderLock = distributedLock.getLock(orderLockName)) {
                            Order order2 = orderService.selectByMerchantOrderNo(orderno);
                            if (order2 != null && OrderStatus.PROCESSING.equals(order2.getOrderStatus())){
                                order.setOrderStatus(orderStatus);
                                order.setOrderNo(channelOrderNo);
                                orderService.paymentOrder(order, new JSONObject());
                                if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                                    orderService.orderToGetWay(order);
                                    try {
                                        wxSendMsgUtils.rechargeSuccess(order);
                                    } catch (Exception e) {
                                        LogPortal.error("{} 七彩交易异步通知 商户订单号[{}]CallBack 微信通知异常", e, traceId, orderno);
                                    }
                                }
                            }
                        }
                    } catch (GetLockFailedException e) {
                        LogPortal.error("{} >>> [DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", orderno, orderLockName);
                        LogPortal.error("{} >>> {} 获取lock失败", e, orderno, orderLockName);
                    } catch (Exception e) {
                        LogPortal.error("{} >>> {} 任务执行出错 ", e, orderno, orderLockName);
                    } finally {
                        if (orderLock) {
                            LogPortal.info(orderno + " >>> " + orderLockName + " finished.");
                            try {
                                distributedLock.releaseLock(orderLockName);
                            } catch (ReleaseLockFailedException e) {
                                LogPortal.error("{} >>> [DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}",orderno, orderLockName);
                                LogPortal.error("{} >>> {} 释放失败", e,orderno, orderLockName);
                            }
                        }
                    }
                } else {
                    LogPortal.info("{} 七彩交易异步通知 商户订单号[{}] 异步通知 不在更新订单状态：[{}]", traceId, orderno, order.getOrderStatus());
                }
            } else {
                LogPortal.error("{} 七彩交易异步通知 商户订单号[{}] 异步通知验签失败", traceId, orderno);
            }
        } catch (Exception e) {
            LogPortal.error("{} 七彩交易异步通知 验签业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
        } finally {
            pw.write("ok");
            pw.flush();
            if (pw != null)
                pw.close();
        }
    }

    @Override
    protected void notifySyncBusinesExec(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        try {
            String attach = JbStringUtil.formatString(request.getParameter("attach"));
            response.sendRedirect(attach + "/gws/loading.html?orderNo=" + orderno);
        } catch (Exception e) {
            LogPortal.error("订单号:{} 七彩交易同步通知 发生{}异常",e,orderno,e.getClass().getName());
        }
    }

    @Override
    protected void agentPayNotifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response, Object obj) {

    }
}
